package com.hqyj.project.service.impl;

import com.hqyj.project.dto.MenuListDto;
import com.hqyj.project.entity.User;
import com.hqyj.project.mapper.UserMapper;
import com.hqyj.project.service.UserService;
import com.hqyj.project.utils.CommonResult;
import com.hqyj.project.utils.MD5Util;
import com.hqyj.project.utils.SendMail;
import com.hqyj.project.vo.EmailVo;
import com.hqyj.project.vo.PageUserVo;
import com.hqyj.project.vo.UserAllVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    public static String code= "";    //定义一个静态变量存储验证码
    @Autowired
    private UserMapper userMapper;

    @Override
    public CommonResult login(String userName, String userPwd) {
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(userName,userPwd);
            subject.login(token);
            subject.checkRoles();       //开启权限
            return new CommonResult(200,"登录成功！");
        }catch (Exception e){
            log.info(e.getMessage());
            User user = (User) SecurityUtils.getSubject().getSession().getAttribute("u");
            if(user==null){
                return new CommonResult(500,"账号不存在！");
            }else {
                return new CommonResult(500,"密码错误！");
            }
        }
    }

    @Override
    public CommonResult logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return new CommonResult(200,"该用户已退出登录");
    }

    /**
    *@ClassNname:
    *@Description:   邮箱验证发送验证码
    *@Author wzk
    *@Date 2023/9/14
    *@Version 1.0
    */
    @Override
    public CommonResult emailCode(String userName,String userEmail) {
        UserAllVo userAllVo = userMapper.emailCode(userName,userEmail);
        if (null == userAllVo){
            return new CommonResult(500,"账号或者邮箱错误");
        }
        code="";    //清空验证码
        Random random = new Random();
        for (int i = 0; i < 5; i++) {    //创建5个验证码
            code += random.nextInt(10);  //添加到验证码
        }
        SendMail email = new SendMail();
        String message = email.sendMail(userEmail, code);//传输用户邮箱和状态码
        return new CommonResult(200,message);
    }

    /**
    *@ClassNname:
    *@Description:邮箱验证进行修改密码
    *@Author wzk
    *@Date 2023/9/15
    *@Version 1.0
    */
    @Override
    public CommonResult updateUserPwd(EmailVo emailvo) {
        String newcode = emailvo.getCode();
        if (!code.equals(newcode)){
            return new CommonResult(500,"验证码错误");
        }
        code="";   //清空验证码
        UUID uuid = UUID.randomUUID();
        String md5Pwd = MD5Util.getMd5Pwd(emailvo.getUserPwd(), uuid.toString());  //密码进行加密
        emailvo.setUserPwd(md5Pwd);     //设置新密码
        emailvo.setUserSalt(uuid.toString());   //设置盐值
        Integer integer = userMapper.updateUserPwd(emailvo);
        if (integer == 0){
            return new CommonResult(500,"修改失败！");
        }
        return new CommonResult(200,"修改成功");
    }

    /**
*@ClassNname:
*@Description:查询用户权限菜单
*@Author wzk
*@Date 2023/9/11
*@Version 1.0
*/
    @Override
    public CommonResult selectUserMenuList(String userName) {
        List<MenuListDto> menuList = userMapper.selectUserMenuList(userName);
        if (null==menuList){  //判断是否为空
            return new CommonResult(500,"查询失败",menuList);
        }

        //定义一个级标题存储集合
        ArrayList<MenuListDto> premissionsRen = new ArrayList<>();
        for (MenuListDto premission : menuList) {
            //判断是否是当前一级标题的子标题(从头开始遍历)
            if (premission.getPid()==0){
                //二级列表存储集合
                ArrayList<MenuListDto> premissionsPerm = new ArrayList<>();
                for (MenuListDto premission1 : menuList) {
                    if (premission1.getPid() == premission.getPremissionId()){
                        premissionsPerm.add(premission1);
                    }
                }
                //将二级标题添加到一级标题中
                premission.setMenuList(premissionsPerm);
                //添加到一级列表
                premissionsRen.add(premission);
            }
        }
        CommonResult data = new CommonResult(200, "查询成功", premissionsRen);
        log.info(premissionsRen.toString());
        return data ; //返回一级标题所在的集合
    }

        /**
        *@ClassNname:
        *@Description:当前登录的用户查询个人信息
        *@Author wzk
        *@Date 2023/9/14
        *@Version 1.0
        */
    @Override
    public CommonResult selectLoginUser(String userName) {
        List<UserAllVo> userAllVo = userMapper.selectLoginUser(userName);
        if (userAllVo.isEmpty()){
            return new CommonResult(500,"查询失败！");
        }
        return new CommonResult(200,"查询成功！",userAllVo);
    }

    /**
    *@ClassNname:
    *@Description:  登录用户修改个人信息
    *@Author wzk
    *@Date 2023/9/14
    *@Version 1.0
    */
    @Override
    public CommonResult updateLoginUser(UserAllVo userAllVo) {
        Integer integer = userMapper.updateLoginUser(userAllVo);
        if (integer==0){
            return new CommonResult(500,"修改失败！");
        }
        return new CommonResult(200,"修改成功！");
    }

    /**
    *@ClassNname:
    *@Description:查询用户信息进行分页
    *@Author wzk
    *@Date 2023/9/12
    *@Version 1.0
    */
    @Override
    public CommonResult selectUserAll(PageUserVo page) {
        List<UserAllVo> userAllVos = userMapper.selectUserAll(page);
        Integer total = userMapper.selectUserTotal(page.getUserRealName(),page.getUserTel());
        userAllVos.get(0).setTotal(total);   //设置信息条数在第一个对象上
        if (userAllVos.isEmpty()){
            return new CommonResult(500,"查询失败",userAllVos);
        }else {
            return new CommonResult(200,"查询成功",userAllVos);
        }
    }
    /**
    *@ClassNname:
    *@Description:逻辑删除用户
    *@Author wzk
    *@Date 2023/9/13
    *@Version 1.0
    */
    @Override
    public CommonResult deleteUser(Integer userId) {
        Integer integer = userMapper.deleteUser(userId);
        if (integer==0){
            return new CommonResult(500,"删除失败");
        }
        return new CommonResult(200,"删除成功");
    }

    /**
    *@ClassNname:
    *@Description: 模糊查询用户
    *@Author wzk
    *@Date 2023/9/13
    *@Version 1.0
    */
    @Override
    public CommonResult selectLickUser(String userRealName, String userTel) {
        PageUserVo<Object> pageUserVo = new PageUserVo<>();   //创建pageVo对象
        pageUserVo.setUserRealName(userRealName);    //设置用户的真实姓名和电话
        pageUserVo.setUserTel(userTel);
        pageUserVo.setCurrentPage(1);   //设置分页查询起始页码和页面条数
        pageUserVo.setCurrentSize(5);
        //通过电话和名字模糊查询用户
        List<UserAllVo> userAllVos = userMapper.selectUserAll(pageUserVo);
        if (userAllVos.isEmpty()){    //判断是否为空
            return new CommonResult(200,"查无此人！");
        }
        Integer integer = userMapper.selectUserTotal(userRealName,userTel);//进行查询用户总条数，进行分页
        userAllVos.get(0).setTotal(integer);      //存放页面总条数在第一个对象里
        return new CommonResult(200,"查询成功！",userAllVos);
    }

    /**
    *@ClassNname:
    *@Description:修改用户信息
    *@Author wzk
    *@Date 2023/9/13
    *@Version 1.0
    */
    @Override
    public CommonResult updateUser(UserAllVo userAllVo) {
//        //获取不萌id，修改部门
//        Integer deptId= userMapper.selectDeptId(userAllVo.getDeptName());
//        Integer roleId = userMapper.selectRoleId(userAllVo.getRoleName());
//        //设置用户角色id和部门id
//        userAllVo.setDeptId(deptId);
//        userAllVo.setRealId(roleId);
        Integer integer = userMapper.updateUser(userAllVo);
        if (integer == 0){
            return new CommonResult(500,"修改失败！");
        }
        return new CommonResult(200,"修改成功！");
    }


    /**
    *@ClassNname:
    *@Description:   插入新用户
    *@Author wzk
    *@Date 2023/9/14
    *@Version 1.0
    */
    @Override
    public CommonResult insertUser(UserAllVo userAllVo) {
        String userPwd = userAllVo.getUserPwd();
        UUID uuid = UUID.randomUUID();    //创建uuid，确定盐值
        String md5Pwd = MD5Util.getMd5Pwd(userPwd, uuid.toString());  //密码加密
        userAllVo.setUserPwd(md5Pwd);         //从新设置密码和盐值
        userAllVo.setUserSalt(uuid.toString());
        Integer integer = userMapper.insertUser(userAllVo);
        Integer integer1 = userMapper.insertRole(userAllVo.getUserRealName(), md5Pwd, userAllVo.getRoleName());//传入用姓名和密码进行添加用户角色
        if (integer==0 || integer1==0){
            return new CommonResult(500,"用户录入失败！");
        }
        return new CommonResult(200,"用户录入成功");
    }


    /**
    *@ClassNname:
    *@Description: 查询账号是否已经存在
    *@Author wzk
    *@Date 2023/9/15
    *@Version 1.0
    */
    @Override
    public CommonResult duplicateUserName(String userName) {
        User user = userMapper.selectUserByUserName(userName);
        if (user == null){
            return new CommonResult(200,"账号不存在");
        }
        return new CommonResult(500,"账号已存在");
    }
}
